package com.yexx.apisvr.app.config.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 自定义限流拦截
 *
 * @date 2020/11/16 18:31
 */
@Component
public class SentinelBlockHandler implements BlockExceptionHandler {

    public final static String DYNAMIC_CODE = "{\"code\": %s, \"message\": \"%s\"}";

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        // BlockException 异常接口，其子类为Sentinel五种规则异常的实现类 40050
        // AuthorityException 授权异常 40051
        // DegradeException 降级异常 40052
        // FlowException 限流异常 40053
        // ParamFlowException 参数限流异常 40054
        // SystemBlockException 系统负载异常 40055
        String json;
        if (e instanceof AuthorityException) {
            json = String.format(DYNAMIC_CODE, 40051, "授权异常");
        } else if (e instanceof DegradeException) {
            json = String.format(DYNAMIC_CODE, 40052, "接口降级");
        } else if (e instanceof FlowException) {
            json = String.format(DYNAMIC_CODE, 40053, "接口限流");
        } else if (e instanceof ParamFlowException) {
            json = String.format(DYNAMIC_CODE, 40054, "接口降级");
        } else if (e instanceof SystemBlockException) {
            json = String.format(DYNAMIC_CODE, 40055, "系统负载异常");
        } else {
            json = String.format(DYNAMIC_CODE, 50000, "error");
        }

        response.setContentType("application/json;charset=utf-8");
        try (PrintWriter out = response.getWriter()) {
            out.write(json);
            out.flush();
        }
    }
}
